package com.ahcfl.controller;

import com.ahcfl.dto.PageBean;
import com.ahcfl.dto.ResponseWrap;
import com.ahcfl.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/upload")
    public ResponseWrap upload(HttpServletRequest request, MultipartFile file){

        String filename = file.getOriginalFilename();
        String path = request.getServletContext().getRealPath("/file/"+filename);
        System.out.println(path);
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //文件数据入库
        com.ahcfl.pojo.File filePojo = new com.ahcfl.pojo.File();
        filePojo.setFileName(filename);
        //获取文件地址
        String httpUrl = "http://localhost:8080/file/"+filename;
        filePojo.setHttpUrl(httpUrl);

        //截取文件类型
        String type = filename.substring(filename.lastIndexOf("."));
        filePojo.setType(type);

        fileService.saveFile(filePojo);

        return new ResponseWrap(true);
    }


    @RequestMapping("/findFileByPage")
    public ResponseWrap findFileByPage(int pageNum, int pageSize){

        PageBean<com.ahcfl.pojo.File> pageBean = fileService.findFileByPage(pageNum,pageSize);

        return new ResponseWrap(pageBean);
    }
}
